#!/usr/bin/env python
# encoding: utf-8

from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *

import configparser
import os, time, random

from ui.axisDock import Ui_DockWidget

class axisDock(QDockWidget, Ui_DockWidget):
    signal_name_changed = pyqtSignal(str, str)
    signal_pos_changed = pyqtSignal(str, str)
    signal_enable_changed = pyqtSignal(str, bool)

    configfile = os.getcwd()+'/conf/axis.ini'
    config_axis = None

    def __init__(self, parent=None):
        super(axisDock, self).__init__(parent)
        self.setupUi(self)
        self.setWindowTitle('自定义运动轴')
        self.setMinimumHeight(150)
        self.setMinimumWidth(450)

        self.list_verticalLayout = []
        self.readConfig()

        self.pushButton_save.clicked.connect(self.writeConfig)
        self.uiLoad()

    def uiLoad(self):
        self.lineEdit_name_dict = {}
        self.lineEdit_pos_dict = {}
        self.checkBox_enable_dict = {}
        i = 0
        config_axis = self.config_axis
        for k in config_axis:
            if len(k) == 1:
                print(k)
                # 获取信息
                item = config_axis[k]
                name = item['name'] if 'name' in item else ''
                pos = item['pos'] if 'pos' in item else ''
                enable = int(item['enable']) if 'enable' in item else 0
                # 创建控件
                lineEdit_name = QLineEdit(name)
                lineEdit_name.textChanged.connect(self.textChangedName)
                lineEdit_pos = QLineEdit(pos)
                lineEdit_pos.textChanged.connect(self.textChangedPos)
                checkBox_enable = QCheckBox("启用")
                checkBox_enable.setCheckState(enable)
                checkBox_enable.setTristate(False)
                checkBox_enable.stateChanged.connect(self.stateChangedEnable)
                # 添加控件
                self.gridLayout_axis.addWidget(QLabel('名称：'), i, 0, 1, 1)
                self.gridLayout_axis.addWidget(lineEdit_name, i, 1, 1, 1)
                self.gridLayout_axis.addWidget(QLabel('点位：'), i, 2, 1, 1)
                self.gridLayout_axis.addWidget(lineEdit_pos, i, 3, 1, 1)
                self.gridLayout_axis.addWidget(checkBox_enable, i, 4, 1, 1)
                # 保存控件
                self.lineEdit_name_dict[k] = lineEdit_name
                self.lineEdit_pos_dict[k] = lineEdit_pos
                self.checkBox_enable_dict[k] = checkBox_enable
                i += 1


    def writeConfig(self):
        """写入配置文件"""
        try:
            config = configparser.RawConfigParser()
            for k in self.config_axis:
                if len(k) == 1:
                    config.add_section(k)
                    config.set(k, "name", str(self.lineEdit_name_dict[k].text()))
                    config.set(k, "pos", str(self.lineEdit_pos_dict[k].text()))
                    config.set(k, "enable", int(self.checkBox_enable_dict[k].checkState()))
            with open(self.configfile, 'w') as configfile:
                config.write(configfile)
            QMessageBox.information(self,"提示","保存成功", QMessageBox.Yes)
        except Exception as e:
            QMessageBox.warning(self,"错误","%s"%e, QMessageBox.Yes)

    def readConfig(self):
        """读取配置文件"""
        try:
            config = configparser.ConfigParser()
            try:
                config.read(self.configfile, encoding="utf-8-sig")
            except:
                config.read(self.configfile )
            self.config_axis = config
        except Exception as e:
            QMessageBox.warning(self, "错误", "%s" % e, QMessageBox.Yes)
            
    def textChangedName(self, txt): 
        obj = self.sender() # 获取发射信号的对象
        for k in self.lineEdit_name_dict:
            if self.lineEdit_name_dict[k] == obj:
                self.signal_name_changed.emit(k, txt)
                break

    def textChangedPos(self, txt): 
        obj = self.sender() # 获取发射信号的对象
        for k in self.lineEdit_pos_dict:
            if self.lineEdit_pos_dict[k] == obj:
                self.signal_pos_changed.emit(k, txt)
                break

    def stateChangedEnable(self, state): 
        obj = self.sender() # 获取发射信号的对象
        for k in self.checkBox_enable_dict:
            if self.checkBox_enable_dict[k] == obj:
                self.signal_enable_changed.emit(k, state)
                break

